﻿using Pay.IService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Pay.DTO;
using Pay.TO;
using Pay.Token.Utils;
using System.Threading.Tasks;
using Pay.Core;
using Pay.Service;
using Autofac;

namespace Pay.Token.Controllers {
    /// <summary>
    /// 下单
    /// </summary>
    [AppAuthorize("Member")]
    public class OrderController : GeneralController {
        private IProductService _iProductService;
        private IShippingAddressService _iShippingAddressService;
        private IOrderService _iOrderService;
        private IRegionService _iRegionService;
        private IOrderModelCache _iOrderModelCache;
        private IComponentContext _iComponentContext;
        private IRedRecordService _iRedRecordService;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="iProductService"></param>
        /// <param name="iShippingAddressService"></param>
        /// <param name="iOrderService"></param>
        /// <param name="componentContext"></param>
        /// <param name="iRegionService"></param>
        /// <param name="iOrderModelCache"></param>
        /// <param name="iRedRecordService"></param>
        public OrderController(IProductService iProductService, IShippingAddressService iShippingAddressService,
                               IOrderService iOrderService, IComponentContext componentContext,
                               IRegionService iRegionService, IOrderModelCache iOrderModelCache,
                               IRedRecordService iRedRecordService) {
            _iProductService = iProductService;
            _iShippingAddressService = iShippingAddressService;
            _iOrderService = iOrderService;
            _iRegionService = iRegionService;
            _iComponentContext = componentContext;
            _iOrderModelCache = iOrderModelCache;
            _iRedRecordService = iRedRecordService;
        }
        /// <summary>
        /// 订单调起微信支付回调
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous, HttpGet]
        public ActionResult PayFinish() {
            return View();
        }
        /// <summary>
        /// 确认订单----》多单
        /// </summary>
        /// <returns></returns>
        [HttpGet, AllowAnonymous]
        public ActionResult ConfirmOrder(long? addressId, string wxOpenId) {
            shippingaddress_dto shippingAddress = null;
            decimal total_amount = 0;
            string cache_no = GetCookieValue("cache_no");
            cache_no = (UserId > 0 ? UserId.ToString() : cache_no);
            var checkout = _iOrderModelCache.GetOrderModelCache<token_check_out_model>(cache_no);
            //缓存失效跳转到商城首页
            if (checkout == null)
                return Redirect("/DistributionMall/Index");
            bool is_login = (UserId > 0 ? true : false);
            if (is_login) {
                shippingAddress = _iShippingAddressService.GetDefaultAddress(UserId);
                if (shippingAddress != null)
                    checkout.shipping_address_id = shippingAddress.id;
                if (addressId.HasValue && addressId.Value > 0) {
                    shippingAddress = _iShippingAddressService.GetById(addressId.Value);
                    checkout.shipping_address_id = addressId.Value;
                }
                var redRecord = _iRedRecordService.GetUser(UserId);
                if (redRecord != null)
                    checkout.total_red_drill = redRecord.present_red_drill;
            } else {
                if (addressId.HasValue && addressId.Value > 0) {
                    shippingAddress = checkout.shipping[addressId];
                    string region_name = _iRegionService.GetRegionNames(shippingAddress.region_id);
                    shippingAddress.region = new region_dto { region_name = region_name };
                }
            }
            foreach (var order in checkout.orders) {
                decimal max_freight = 0, temp_amount = 0;
                foreach (var item in order.order_items) {
                    //纯现金价格
                    var product_ex = _iProductService.GetCalculateExForActivity(item.product_id, item.sku_id, false, true);
                    item.price = product_ex.price;
                    //活动价格
                    var activity_product = _iProductService.GetCalculateExForActivity(item.product_id, item.sku_id);
                    item.activity_price = activity_product.price;
                    item.red_drill = activity_product.activity_red_drill;
                    //匿名购买活动商品，统一纯现金购买。
                    if (UserId == 0) {
                        item.activity_price = item.price;
                        item.red_drill = 0;
                        if (activity_product.activity_type == 4)
                            return Redirect("/DistributionMall/Index");
                    }
                    if (activity_product.activity_type == 3)
                        checkout.is_all_drill = 2;
                    else if (activity_product.activity_type == 4)
                        checkout.is_all_drill = 1;
                    if (product_ex.freight > max_freight)
                        max_freight = product_ex.freight;
                    if (product_ex.product_source > 0) {
                        order.is_seas = true;
                        if (!checkout.is_seas)
                            checkout.is_seas = true;
                    }
                    if (item.activity_price > 0) {
                        temp_amount += item.activity_price * item.num;
                    }
                }
                order.freight = max_freight;
                order.total_amount = temp_amount + order.freight;
                total_amount += order.total_amount;
                order.total_red_drill = order.order_items.Sum(c => c.red_drill);
            }
            checkout.product_red_drill = checkout.orders.Sum(c => c.total_red_drill);
            if (shippingAddress != null) {
                if ((checkout.shipping.Keys.Count == 0 || !checkout.shipping.ContainsKey(checkout.shipping_address_id)))//新增
                    checkout.shipping.Add(checkout.shipping_address_id, shippingAddress);
                else if ((checkout.shipping.Keys.Count > 0 && checkout.shipping.ContainsKey(checkout.shipping_address_id)))//修改
                    checkout.shipping[checkout.shipping_address_id] = shippingAddress;
            }
            checkout.total_amount = total_amount;
            checkout.wx_open_id = wxOpenId;
            _iOrderModelCache.SetOrderModelCache(checkout, cache_no);
            ViewBag.Checkout = checkout;
            ViewBag.ShippingAddress = shippingAddress;
            ViewBag.WXOpenId = wxOpenId;
            ViewBag.IsLogin = is_login;
            ViewBag.img_url = RequestMethod.token_imgurl;
            return View();
        }
        /// <summary>
        /// 支付----》多单
        /// </summary>
        /// <param name="rqModel"></param>
        /// <returns></returns>
        [HttpPost, AllowAnonymous]
        public async Task<JsonResult> Pay(token_order_pay_model rqModel) {
            var api_result = new ApiResultMessage { result_msg = "操作成功" };
            string cache_no = GetCookieValue("cache_no");
            cache_no = UserId > 0 ? UserId.ToString() : cache_no;
            var checkout = _iOrderModelCache.GetOrderModelCache<token_check_out_model>(cache_no);
            if (checkout == null)
                throw new ServerErrorException("订单数据已过期，请刷新页面");
            checkout.ip = GetHostAddress();
            checkout.buy_user_id = UserId;
            checkout.total_amount = rqModel.total_amount;
            checkout.is_cash_pay = (rqModel.pay_type == 3);
            //匿名购买商品，强制用户纯现金购买
            if (UserId == 0)
                checkout.is_cash_pay = true;
            if (checkout.is_cash_pay)
                checkout.product_red_drill = 0;
            var rq_order_item = rqModel.orders.SelectMany(c => c.order_items).ToList();
            int i = 0;
            foreach (var order in checkout.orders) {
                order.remark = rqModel.orders[i].remark;
                foreach (var item in order.order_items) {
                    var order_item = rq_order_item.FirstOrDefault(s => s.product_id == item.product_id && s.sku_id == item.sku_id);
                    if (order_item == null) continue;
                    item.num = order_item.quantity;
                    if (checkout.is_cash_pay)
                        item.red_drill = 0;
                }
                i++;
            }
            var model = _iOrderService.GetTokenMallPayOrder(checkout);
            foreach (var order in model.orders) {
                order.binds.Clear();
                foreach (var item in order.order_items) {
                    var profits = new List<bind_merchant_item>();
                    if (item.active_type == 1) {
                        var member_id = (item.distribution_id.HasValue && item.distribution_id.Value > 0 ? item.distribution_id.Value : UserId);
                        profits = UpGradeFade.CalcMallProfits(_iComponentContext, member_id, UserType.tokenMaker, item);
                    } else if (item.active_type == 4) {
                        //全红砖兑换不产生分润
                    } else {
                        if (item.active_type == 3)
                            item.isCashPay = checkout.is_cash_pay;
                        profits = DistributionFade.CalcMallProfits(_iComponentContext, order.buyer, item);
                    }
                    if (profits.Count > 0)
                        order.binds.AddRange(profits);
                }
            }
            if (model.shipping == null) {
                throw new ServerErrorException("请选择收货地址");
            }
            if (checkout.is_seas) {
                if (string.IsNullOrEmpty(model.shipping.id_card) || string.IsNullOrEmpty(model.shipping.real_name) || model.shipping.real_name != model.shipping.ship_to) {
                    api_result.result_code = 2000;
                    api_result.result_msg = (checkout.shipping_address_id.HasValue ? checkout.shipping_address_id.Value.ToString() : "");
                    return Json(api_result, JsonRequestBehavior.AllowGet);
                }
                //    throw new ServerErrorException("购买跨境商品，请填写身份证号和真实姓名！");
                //if (model.shipping.real_name != model.shipping.ship_to)
                //    throw new ServerErrorException("收货人和真实姓名必须一致");
            }
            var result = await HChannelApi.Current.PostApi<mall_h5_result>(model);
            if (result == null) {
                throw new ServerErrorException("网络异常");
            }
            if (result.result_code == 1000) {
                if (model.is_wx_pub_account_pay) {//公众号支付
                    api_result.result_msg = result.pay_info;
                } else {
                    api_result.result_msg = result.code_url;
                }
                api_result.result_code = 1000;
            } else {
                throw new ServerErrorException(result.result_msg);
            }
            return Json(api_result, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 待支付
        /// </summary>
        /// <param name="rqModel"></param>
        /// <returns></returns>
        [HttpPost, AllowAnonymous]
        public async Task<JsonResult> WaitPay(token_mall_to_pay_order_model rqModel) {
            var api_result = new ApiResultMessage { result_msg = "操作成功" };
            var checkout = new token_check_out_model {
                wx_open_id = rqModel.wx_open_id,
                orders = new List<token_order_model> {
                    new token_order_model{
                        order_no = rqModel.order_no
                    }
                }
            };
            checkout.ip = GetHostAddress();
            var model = _iOrderService.GetTokenMallPayOrder(checkout);
            var result = await HChannelApi.Current.PostApi<mall_h5_result>(model);
            if (result == null) {
                throw new ServerErrorException("网络异常");
            }
            if (result.result_code == 1000) {
                if (model.is_wx_pub_account_pay) {//公众号支付
                    api_result.result_msg = result.pay_info;
                } else {
                    api_result.result_msg = result.code_url;
                }
                api_result.result_code = 1000;
            } else {
                throw new ServerErrorException(result.result_msg);
            }
            return Json(api_result, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 0立即购买 1购物车结算
        /// </summary>
        /// <param name="model"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        [HttpPost, AllowAnonymous]
        public JsonResult AddBuy(List<AddCartModel> model, int type = 0) {
            model.ForEach(s => { s.merchant_id = UserId; });
            var order_model = _iOrderService.AddBuy(model, type);
            string cache_no = GetCookieValue("cache_no");
            cache_no = (UserId > 0 ? UserId.ToString() : cache_no);
            _iOrderModelCache.SetOrderModelCache(order_model, cache_no);
            return Json(ResultToJson.Json(order_model), JsonRequestBehavior.AllowGet);
        }
    }
}